#!/usr/bin/env python3
"""
简化的 Windows 打包脚本
安装依赖后重新启动进程以确保模块可以正确导入
"""

import os
import sys
import subprocess
from pathlib import Path


def install_dependencies():
    """安装项目依赖"""
    print("正在安装项目依赖...")
    
    dependencies = ["PySide6>=6.6.0", "Pillow>=10.0.0", "pyinstaller"]
    
    for dep in dependencies:
        print(f"安装 {dep}...")
        try:
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", dep
            ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            print(f"✓ {dep} 安装完成")
        except subprocess.CalledProcessError:
            print(f"✗ {dep} 安装失败")
            return False
    
    return True


def check_dependencies():
    """检查依赖是否已安装"""
    required_modules = {
        'PySide6': 'PySide6',
        'PIL': 'Pillow', 
        'PyInstaller': 'pyinstaller'
    }
    
    missing = []
    for module_name, package_name in required_modules.items():
        try:
            __import__(module_name)
            print(f"✓ {package_name} 已安装")
        except ImportError:
            print(f"✗ {package_name} 未安装")
            missing.append(package_name)
    
    return len(missing) == 0, missing


def build_exe():
    """构建可执行文件"""
    print("\n开始构建可执行文件...")
    
    # 清理之前的构建
    import shutil
    for dir_name in ["build", "dist"]:
        if os.path.exists(dir_name):
            shutil.rmtree(dir_name)
            print(f"✓ 已清理 {dir_name}")
    
    # 构建命令
    build_cmd = [
        "pyinstaller",
        "--onefile",
        "--windowed", 
        "--name=SmartClipboard",
        "--distpath=dist",
        "--workpath=build",
        "--add-data=src;src",
        "--hidden-import=PySide6.QtCore",
        "--hidden-import=PySide6.QtWidgets",
        "--hidden-import=PySide6.QtGui",
        "--hidden-import=PIL",
        "--hidden-import=sqlite3",
        "run.py"
    ]
    
    try:
        subprocess.check_call(build_cmd)
        print("✓ 构建完成！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 构建失败: {e}")
        return False


def create_install_script():
    """创建安装脚本"""
    os.makedirs("dist", exist_ok=True)
    
    install_content = '''@echo off
echo 智能剪切板安装程序
echo.

set "INSTALL_DIR=%LOCALAPPDATA%\\SmartClipboard"
set "DESKTOP_LINK=%USERPROFILE%\\Desktop\\智能剪切板.lnk"

echo 创建安装目录...
if not exist "%INSTALL_DIR%" mkdir "%INSTALL_DIR%"

echo 复制文件...
copy "SmartClipboard.exe" "%INSTALL_DIR%\\SmartClipboard.exe"

echo 创建桌面快捷方式...
powershell "$WshShell = New-Object -comObject WScript.Shell; $Shortcut = $WshShell.CreateShortcut('%DESKTOP_LINK%'); $Shortcut.TargetPath = '%INSTALL_DIR%\\SmartClipboard.exe'; $Shortcut.Save()"

echo.
echo 安装完成！桌面已创建快捷方式
pause
'''
    
    with open("dist/install.bat", "w", encoding="gbk") as f:
        f.write(install_content)
    
    print("✓ 安装脚本创建完成")


def main():
    """主函数"""
    print("=" * 50)
    print("智能剪切板 Windows 简化打包脚本")
    print("=" * 50)
    
    # 检查依赖
    deps_ok, missing = check_dependencies()
    
    if not deps_ok:
        print(f"\n缺少依赖: {', '.join(missing)}")
        
        # 如果是第一次运行且缺少依赖，安装依赖然后重新启动脚本
        if "--retry" not in sys.argv:
            print("正在安装缺少的依赖...")
            if install_dependencies():
                print("\n依赖安装完成，重新启动打包过程...")
                # 重新启动脚本
                subprocess.call([sys.executable, __file__, "--retry"])
                return 0
            else:
                print("依赖安装失败，请手动安装")
                return 1
        else:
            print("依赖仍然缺失，请手动检查")
            return 1
    
    # 构建可执行文件
    if not build_exe():
        return 1
    
    # 创建安装脚本
    create_install_script()
    
    print("\n" + "=" * 50)
    print("打包完成！")
    print("=" * 50)
    print("可执行文件: dist/SmartClipboard.exe")
    print("安装脚本: dist/install.bat")
    
    return 0


if __name__ == "__main__":
    sys.exit(main()) 